<!--
/**
 * StudyList 组件
 * 
 * DICOM Studies 查询和列表显示组件
 * 
 * @author yangzhixin
 */
-->

<template>
  <div class="study-list">
    <!-- 面板头部 -->
    <div class="panel-header">
      <h3>Studies 列表</h3>
      <span class="study-count">{{ studies.length }} 个研究</span>
    </div>

    <!-- 搜索区域（折叠式） -->
    <div class="search-section">
      <button class="search-toggle" @click="searchExpanded = !searchExpanded">
        <span class="toggle-icon">{{ searchExpanded ? '🔍' : '🔍' }}</span>
        <span class="toggle-text">{{ searchExpanded ? '收起查询' : '展开查询' }}</span>
      </button>
      
      <div v-show="searchExpanded" class="search-inputs">
        <input
          v-model="searchParams.patientName"
          type="text"
          placeholder="患者姓名"
          class="search-input"
        />
        <input
          v-model="searchParams.patientID"
          type="text"
          placeholder="患者ID"
          class="search-input"
        />
        <input
          v-model="searchParams.studyDate"
          type="text"
          placeholder="检查日期 (YYYYMMDD)"
          class="search-input"
        />
        <input
          v-model="searchParams.modality"
          type="text"
          placeholder="模态"
          class="search-input"
        />
        <div class="search-actions">
          <button
            class="btn-search"
            :disabled="!isConfigured || isLoading"
            @click="handleSearch"
          >
            <span v-if="isLoading" class="loading-spinner">⏳</span>
            <span v-else>🔍</span>
            {{ isLoading ? '查询中...' : '查询' }}
          </button>
          <button
            class="btn-clear"
            :disabled="isLoading"
            @click="handleClear"
          >
            🗑️ 清空
          </button>
        </div>
      </div>
    </div>

    <!-- Studies 列表 -->
    <div class="studies-list">
      <!-- 加载中 -->
      <div v-if="isLoading" class="empty-studies">
        <div class="empty-icon">⏳</div>
        <div class="empty-text">查询中...</div>
      </div>

      <!-- 未配置 -->
      <div v-else-if="!isConfigured" class="empty-studies">
        <div class="empty-icon">☁️</div>
        <div class="empty-text">未配置 DICOMweb 服务器</div>
      </div>

      <!-- 空结果 -->
      <div v-else-if="studies.length === 0 && !error" class="empty-studies">
        <div class="empty-icon">📁</div>
        <div class="empty-text">
          {{ hasSearched ? '未找到匹配的 Studies' : '请输入查询条件' }}
        </div>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="empty-studies error">
        <div class="empty-icon">❌</div>
        <div class="empty-text">{{ error }}</div>
        <button class="btn-retry" @click="handleSearch">重试</button>
      </div>

      <!-- Study 卡片列表 -->
      <div
        v-else
        v-for="study in studies"
        :key="study.studyInstanceUID"
        class="study-item"
        :class="{ 'active': selectedStudy === study.studyInstanceUID }"
        @click="handleSelectStudy(study)"
      >
        <div class="study-info">
          <div class="study-title">
            {{ study.patientName || '未知患者' }}
          </div>
          <div class="study-details">
            <span class="detail-item">
              {{ study.modality || 'N/A' }}
            </span>
            <span class="detail-item">
              {{ formatDate(study.studyDate) }}
            </span>
          </div>
          <div class="study-meta">
            <span class="meta-item">
              患者ID: {{ study.patientID || 'N/A' }}
            </span>
          </div>
          <div class="study-stats">
            <span class="stat-badge series">
              {{ study.numberOfSeries || 0 }} Series
            </span>
            <span class="stat-badge images">
              {{ study.numberOfInstances || 0 }} 图像
            </span>
          </div>
          <div class="study-description">
            {{ study.studyDescription || '无描述' }}
          </div>
        </div>
        
        <!-- 选中标记 -->
        <div v-if="selectedStudy === study.studyInstanceUID" class="study-selected-icon">
          ✓
        </div>
        
        <!-- 加载按钮 -->
        <button
          class="btn-load"
          @click.stop="handleLoadStudy(study)"
        >
          👁️ 加载
        </button>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="studies.length > 0 && showPagination" class="panel-footer">
      <button
        class="btn-page"
        :disabled="currentPage === 1 || isLoading"
        @click="handlePreviousPage"
      >
        ◀
      </button>
      <span class="page-info">
        {{ currentPage }} / {{ totalPages }}
      </span>
      <button
        class="btn-page"
        :disabled="currentPage === totalPages || isLoading"
        @click="handleNextPage"
      >
        ▶
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import type { StudyInfo } from '@/composables/useDICOMweb';

/**
 * 组件属性
 */
interface Props {
  /** Studies 列表 */
  studies?: StudyInfo[];
  /** 是否正在加载 */
  isLoading?: boolean;
  /** 是否已配置 */
  isConfigured?: boolean;
  /** 错误信息 */
  error?: string | null;
  /** 是否显示分页 */
  showPagination?: boolean;
  /** 每页条目数 */
  pageSize?: number;
}

const props = withDefaults(defineProps<Props>(), {
  studies: () => [],
  isLoading: false,
  isConfigured: false,
  error: null,
  showPagination: false,
  pageSize: 20,
});

/**
 * 组件事件
 */
interface Emits {
  (e: 'search', params: any): void;
  (e: 'select-study', study: StudyInfo): void;
  (e: 'load-study', study: StudyInfo): void;
  (e: 'page-change', page: number): void;
}

const emit = defineEmits<Emits>();

// 搜索参数
const searchParams = ref({
  patientName: '',
  patientID: '',
  studyDate: '',
  modality: '',
});

// 状态
const selectedStudy = ref<string | null>(null);
const hasSearched = ref(false);
const currentPage = ref(1);
const searchExpanded = ref(false);

// 计算属性
const totalPages = computed(() => {
  return Math.ceil(props.studies.length / props.pageSize);
});

/**
 * 处理搜索
 */
const handleSearch = () => {
  hasSearched.value = true;
  currentPage.value = 1;
  
  // 构建查询参数（过滤空值）
  const params: any = {};
  if (searchParams.value.patientName) {
    params.patientName = searchParams.value.patientName;
  }
  if (searchParams.value.patientID) {
    params.patientID = searchParams.value.patientID;
  }
  if (searchParams.value.studyDate) {
    params.studyDate = searchParams.value.studyDate;
  }
  if (searchParams.value.modality) {
    params.modality = searchParams.value.modality;
  }

  emit('search', params);
};

/**
 * 处理清空
 */
const handleClear = () => {
  searchParams.value = {
    patientName: '',
    patientID: '',
    studyDate: '',
    modality: '',
  };
  hasSearched.value = false;
  selectedStudy.value = null;
};

/**
 * 处理选择 Study
 */
const handleSelectStudy = (study: StudyInfo) => {
  selectedStudy.value = study.studyInstanceUID;
  emit('select-study', study);
};

/**
 * 处理加载 Study
 */
const handleLoadStudy = (study: StudyInfo) => {
  emit('load-study', study);
};

/**
 * 处理上一页
 */
const handlePreviousPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    emit('page-change', currentPage.value);
  }
};

/**
 * 处理下一页
 */
const handleNextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
    emit('page-change', currentPage.value);
  }
};

/**
 * 格式化日期
 */
const formatDate = (dateStr?: string): string => {
  if (!dateStr) return 'N/A';
  
  // DICOM 日期格式: YYYYMMDD
  if (dateStr.length === 8) {
    const year = dateStr.substring(0, 4);
    const month = dateStr.substring(4, 6);
    const day = dateStr.substring(6, 8);
    return `${year}-${month}-${day}`;
  }
  
  return dateStr;
};

// 监听 studies 变化，重置选择
watch(
  () => props.studies,
  () => {
    selectedStudy.value = null;
  }
);
</script>

<style scoped>
.study-list {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: white;
}

/* 面板头部 */
.panel-header {
  padding: 16px 20px;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f8f9fa;
  flex-shrink: 0;
}

.panel-header h3 {
  margin: 0;
  font-size: 15px;
  font-weight: 600;
  color: #2c3e50;
}

.study-count {
  font-size: 11px;
  color: #fff;
  background: #007bff;
  padding: 4px 10px;
  border-radius: 12px;
  font-weight: 600;
}

/* 搜索区域 */
.search-section {
  border-bottom: 1px solid #e9ecef;
  background: white;
  flex-shrink: 0;
}

.search-toggle {
  width: 100%;
  padding: 12px 20px;
  background: #f8f9fa;
  border: none;
  border-bottom: 1px solid #e9ecef;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.2s;
  font-size: 13px;
  font-weight: 500;
  color: #2c3e50;
}

.search-toggle:hover {
  background: #e9ecef;
}

.toggle-icon {
  font-size: 14px;
}

.toggle-text {
  flex: 1;
  text-align: left;
}

.search-inputs {
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  background: white;
}

.search-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  font-size: 13px;
  transition: border-color 0.2s;
}

.search-input:focus {
  outline: none;
  border-color: #007bff;
}

.search-input::placeholder {
  color: #999;
}

.search-actions {
  display: flex;
  gap: 8px;
  margin-top: 4px;
}

.btn-search,
.btn-clear {
  flex: 1;
  padding: 8px 12px;
  border: none;
  border-radius: 4px;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-search {
  background: #007bff;
  color: white;
}

.btn-search:hover:not(:disabled) {
  background: #0056b3;
}

.btn-search:disabled {
  background: #6c757d;
  cursor: not-allowed;
  opacity: 0.6;
}

.btn-clear {
  background: #f8f9fa;
  color: #666;
  border: 1px solid #e9ecef;
}

.btn-clear:hover:not(:disabled) {
  background: #e9ecef;
}

.loading-spinner {
  display: inline-block;
  animation: spin 1.5s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* Studies 列表 */
.studies-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
}

/* Study 卡片 */
.study-item {
  border: 2px solid #e9ecef;
  border-radius: 8px;
  margin-bottom: 12px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
  background: white;
}

.study-item:hover {
  border-color: #007bff;
  background: #f8f9ff;
  transform: translateX(2px);
  box-shadow: 0 2px 8px rgba(0, 123, 255, 0.15);
}

.study-item.active {
  border-color: #007bff;
  background: #e7f3ff;
  box-shadow: 0 2px 8px rgba(0, 123, 255, 0.2);
}

.study-info {
  flex: 1;
  padding-right: 40px;
}

.study-title {
  font-size: 14px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 6px;
  line-height: 1.4;
}

.study-details {
  display: flex;
  gap: 8px;
  margin-bottom: 6px;
  flex-wrap: wrap;
}

.detail-item {
  font-size: 11px;
  color: #6c757d;
  background: #f8f9fa;
  padding: 2px 8px;
  border-radius: 4px;
  font-weight: 500;
}

.study-meta {
  margin-bottom: 6px;
}

.meta-item {
  font-size: 11px;
  color: #999;
  font-family: 'Courier New', monospace;
}

.study-stats {
  display: flex;
  gap: 6px;
  margin-bottom: 6px;
}

.stat-badge {
  font-size: 10px;
  padding: 3px 8px;
  border-radius: 10px;
  font-weight: 600;
}

.stat-badge.series {
  background: #e3f2fd;
  color: #1976d2;
}

.stat-badge.images {
  background: #f3e5f5;
  color: #7b1fa2;
}

.study-description {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
  margin-top: 4px;
}

.study-selected-icon {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 24px;
  height: 24px;
  background: #28a745;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: bold;
}

.btn-load {
  position: absolute;
  bottom: 8px;
  right: 8px;
  padding: 4px 10px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 11px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-load:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(102, 126, 234, 0.4);
}

/* 空状态 */
.empty-studies {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-studies.error {
  color: #dc3545;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 12px;
  opacity: 0.5;
}

.empty-text {
  font-size: 13px;
  color: #6c757d;
  margin-bottom: 12px;
}

.btn-retry {
  padding: 8px 16px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-retry:hover {
  background: #0056b3;
}

/* 面板底部（分页） */
.panel-footer {
  padding: 12px 16px;
  border-top: 1px solid #e9ecef;
  background: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  flex-shrink: 0;
}

.btn-page {
  width: 32px;
  height: 32px;
  background: white;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 12px;
  color: #2c3e50;
}

.btn-page:hover:not(:disabled) {
  background: #007bff;
  color: white;
  border-color: #007bff;
}

.btn-page:disabled {
  opacity: 0.4;
  cursor: not-allowed;
}

.page-info {
  font-size: 12px;
  color: #666;
  font-weight: 500;
  min-width: 60px;
  text-align: center;
}

/* 滚动条美化 */
.studies-list::-webkit-scrollbar {
  width: 6px;
}

.studies-list::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.studies-list::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 3px;
}

.studies-list::-webkit-scrollbar-thumb:hover {
  background: #555;
}
</style>





